package com.sdcx.agrobank.util;

import com.sdcx.agrobank.net.HttpsUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * function:Retrofit的底层是不是就是OKhttp,我给OKhttp设置https的初始化,然后我再把OKhttp对象给Retrofit,Retrofit就可以进行https网络请求
 */
public class RetrofitManager {

    //日志
    private HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);

    //基础网址
    private static String BASE_URL = "https://172.17.8.100/techApi/";
    private Retrofit mRetrofit;
    private static class SingleHolder {
        private static final RetrofitManager _INSTANT = new RetrofitManager(BASE_URL);
    }

    //暴露给外界调用的两个方法,可以省去网络请求的很多环节
    public static RetrofitManager getDefault() {
        return SingleHolder._INSTANT;
    }
    //因为我们Retrofit的接口是不一样的,所以我再通过动态代理生成对象时,我无法知道类名是什么,所以就用到了泛型
    public <T> T create(Class<T> Clazz) {
        return mRetrofit.create(Clazz);
    }

    private RetrofitManager(String baseUrl) {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                //okhttpClinet对象设置给Retrofit时,Retrofit就具备了https的请求
                .client(buildOkhttpClinet())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 让ok支持https,核心的代码
     */
    private OkHttpClient buildOkhttpClinet() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor);
               // .addNetworkInterceptor(loggingInterceptor);

        //支持https证书和域名认证
        HttpsUtils htppsUtils = new HttpsUtils(App.context);
        OkHttpClient.Builder newBuilder = htppsUtils.setCertificateForOkhttp(builder);
        OkHttpClient okHttpClient = newBuilder.build();
        return okHttpClient;
    }

}
